package cn.hxzy.icon.zyinon.service;

import cn.hxzy.icon.zyinon.entity.User;
import cn.hxzy.icon.zyinon.entity.vo.PageBean;
import cn.hxzy.icon.zyinon.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public PageBean<User> findAll(PageBean<User> pageBean){
        Pageable pageable= PageRequest.of(pageBean.getPage()-1, pageBean.getSize(), Sort.by(Sort.Order.desc("createTime")));
        Page<User> all = userRepository.findAll(pageable);
        pageBean.setList(all.getContent());
        pageBean.setCount(all.getTotalElements());
        pageBean.setPageCount(all.getTotalPages());
        return  pageBean;
    }

    public void save(User user){
        userRepository.save(user);
    }

    public void delete(Integer id){
        userRepository.deleteById(id);
    }
    public User findById(Integer id){
        Optional<User> byId = userRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }
    public User findByLoginNameAndLoginPassword(String loginName,String loginPassword){
        Optional<User> byLoginName=  userRepository.findByLoginName( loginName);
        if (byLoginName.isPresent()) {
            User user = byLoginName.get();
            if (user.getLoginPassword().equals(loginPassword)) {
                return user;
            }
        }
        return null;
    }

}
